/*
    This file is part of tPortal.

    tPortal is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    tPortal is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with tPortal.  If not, see <http://www.gnu.org/licenses/>.

    The original code was written by Sebastien Bettinger <sebastien.bettinger@gmail.com>

 */

package net.tinyportal.servlet;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.tinyportal.Constant;
import net.tinyportal.persistence.entity.Layout;
import net.tinyportal.persistence.entity.PortletZone;
import net.tinyportal.portal.PortletHolder;
import net.tinyportal.portal.PortletRender;
import net.tinyportal.service.LayoutService;
import net.tinyportal.service.PortletService;
import net.tinyportal.service.PreferenceService;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/")
public class Portlet2Servlet implements ApplicationContextAware {
	@Autowired
	ApplicationContext applicationContext;

	/**
	 * 
	 */
	private static final long serialVersionUID = 7934374005770615573L;

	/**
	 * Logger
	 */
	private static final Log log = LogFactory.getLog(Portlet2Servlet.class);

	/**
	 * Jsp du portail, définie dans le web.xml
	 */
	private String portalJsp;

	@Autowired
	private PreferenceService preferenceService;

	@Autowired
	private PortletService portletService;

	@Autowired
	private LayoutService layoutService;

	@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Layout p;


		if (layoutService.getAllLayout().isEmpty()) {
			p = new Layout();
			p.setName("Accueil");
			p.setJsp("/WEB-INF/jsp/layout/layout.jsp");
			p.setDefaultLayout(true);
			PortletZone pz = new PortletZone();
			pz.addPortlet("HtmlPresentationPortlet");
			pz.addPortlet("HtmlPresentationPortlet@@2");

			Map<String, PortletZone> m = new HashMap<String, PortletZone>();
			m.put("one", pz);

			p.setPortlet(m);
			layoutService.persist(p);
			
			p = new Layout();
			p.setName("Test");
			p.setJsp("/WEB-INF/jsp/layout/layout.jsp");
			p.setDefaultLayout(true);
			pz = new PortletZone();
			pz.addPortlet("HtmlPresentationPortlet@@3");
			pz.addPortlet("HtmlPresentationPortlet@@4");

			m = new HashMap<String, PortletZone>();
			m.put("one", pz);

			p.setPortlet(m);
			layoutService.persist(p);
		}

		/*
		 * On recupère le layout a afficher
		 */
		if (request.getParameter("page") != null) {
			p = layoutService.getLayout(request.getParameter("page"));
			request.getSession(true).setAttribute("tpPage", p);
		} else {
			p = (Layout) request.getSession(true).getAttribute("tpPage");
		}
		/* Dans le cas ou p n'existe pas, on récupère la page par défaut */
		if (p == null) {
			p = layoutService.getDefaultLayout();
		}
		request.setAttribute("layout", p);

		try {
			/*
			 * On commence par créer/récupérer la session de l'utilisateur,
			 * dans le cas d'un utilisateur non authentifié, on crée simplement une session anonyme
			 */

			Map <String, PortletHolder> resultMap = new HashMap<String, PortletHolder>();
			/*
			 * Affichage
			 * On va parcourir les portlets présent dans l'objet portal
			 * et s'en occuper
			 */
			List<String> portletToRender = layoutService.findAllPortlet(p.getName());
			Set<String> set = new HashSet<String>(portletToRender);
			set.add("LoginPortlet");
			set.add("ListAllPortlet");
			set.add("ManagePage");
			
			PortletRender portletRender;
			for(String portletName: set) {
				request.setAttribute("net.tinyportal.spring.portlet", portletName);
				portletRender = (PortletRender) applicationContext.getBean("portletRender");
				PortletHolder portletHolder = portletRender.render(request, response, portletName);
				resultMap.put(portletName, portletHolder);
			}

			/*
			 * On fait le rendu du portail
			 */
			request.setAttribute(Constant.session_portlet_bean_map, resultMap);
			response.setHeader("Content-Type", "text/html");

			return new ModelAndView("portal");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

}
